package com.woniu.commons.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class JWTUtil {
    public static final String SECRET_KEY = "123456"; //密钥

    public static final long TOKEN_EXPIRE_TIME = 24 * 3600 * 1000L; //过期时间

    public static final long REFRESH_TOKEN_EXPIRE_TIME = 1000 * 3600 * 1000L; //刷新token过期时间

    private static final String ISSUER = "issuer "; //签发人

    //生成token
    public static String generateToken(int userId, String username) {
        Date now = new Date();
        //创建签名算法对象
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法

        String token = JWT.create()
                .withIssuer(ISSUER) //签发人
                .withIssuedAt(now) //签发时间
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXPIRE_TIME)) //过期时间
                .withClaim("userId", userId) //携带信息
                .withClaim("username", username) //携带信息
                .sign(algorithm); //签名
        return token;
    }

    //验证token
    public static TokenEnum verify(String token) {
        try {
            //创建签名算法对象
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);//算法
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER).
                    build();
            verifier.verify(token);

            log.info("token校验成功");
            return TokenEnum.TOKEN_SUCCESS;
        } catch (TokenExpiredException e) {
            log.error("token过期", e);
            return TokenEnum.TOKEN_EXPIRE;
        } catch (Exception e) {
            log.error("token校验失败", e);
            return TokenEnum.TOKEN_BAD;
        }
    }

    //获取token中的userId
    public static int getUserId(String token) {
        try {
            return JWT.decode(token).getClaim("userId").asInt();
        } catch (JWTDecodeException e) {
            e.printStackTrace();
        }
        return 0;
    }

    //获取token中的username
    public static String getUsername(String token) {
        try {
            return JWT.decode(token).getClaim("username").asString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
